package com.service;


import com.mapper.UserDao;
import com.pojo.User;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import com.tools.Constants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.List;


/**
 * service层捕获异常，进行事务处理
 * 事务处理：调用不同dao的多个方法，必须使用同一个connection（connection作为参数传递）
 * 事务完成之后，需要在service层进行connection的关闭，在dao层关闭（PreparedStatement和ResultSet对象）
 * @author Administrator
 *
 */

@Service
public class UserServiceImpl implements UserService{
	private Logger log= LogManager.getLogger(UserServiceImpl.class);

	@Resource
	private UserDao userDao;


	@Override
	public User login(String userCode, String userPassword) {
		User user = null;
		try {
			user=userDao.getLoginUser(userCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//匹配密码
		if(null != user){
			if(!user.getUserPassword().equals(userPassword))
				user = null;
		}
		return user;
	}

	@Override
	public int add(User user) throws Exception {
		int updateRows = userDao.add(user);
		if(updateRows > 0){
			log.info("add success!");
		}else{
			log.info("add failed!");
		}
		return updateRows;
	}

	@Override
	public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
		List<User> userList = null;
		userList = userDao.getUserList(userName,userRole,currentPageNo,pageSize);
		return userList;
	}

	@Override
	public int getUserCount(String userName, int userRole) throws Exception {
		int count = 0;
		count = userDao.getUserCount(userName,userRole);
		return count;
	}

	@Override
	public User selectUserCodeExist(String userCode) {
		User user = null;
		try {
			user = userDao.getLoginUser(userCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public int deleteUserById(Integer delId) throws Exception {
		int count=userDao.deleteUserById(delId);
			if( count> 0){
				log.info("删除成功");
			}else {
				log.info("删除失败");
			}
		return count;
	}

	@Override
	public User getUserById(String id){
		User user = null;
		try{
			user = userDao.getUserById(id);
		}catch (Exception e) {
			e.printStackTrace();
			user = null;
		}
		return user;
	}

	@Override
	public int modify(User user) throws Exception {
		int count=userDao.modify(user);
			if( count> 0){
				log.info("修改成功");
			}else {
				log.info("修改失败");
			}
		return count;
	}

	@Override
	public int updatePwd(int id, String pwd) throws Exception {
		int count=userDao.updatePwd(id,pwd);
			if(count> 0) {
				log.info("修改密码成功");
			}else {
				log.info("修改密码失败");
			}
		return count;
	}
}
